import * as XLSX from 'xlsx'

export function toTable(file, columns) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.onload = (e) => {
      /* 解析数据 */
      const bstr = e.target.result;
      const wb = XLSX.read(bstr, {type: 'binary'});
      /* 获取文件的第一个工作表（WorkSheet） */
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      /* 数组转换 */
      const data = XLSX.utils.sheet_to_json(ws, {header: 1});

      const rtn = analysisTableData(data, columns)
      resolve(rtn)
    }
    reader.readAsBinaryString(file.raw);
  })
}

function analysisTableData(data, columns) {
  // 头
  const header = data[0]
  // 数据
  const list = data.slice(1, data.length)
  // 表格数据
  const dataList = []

  const mapper = {}
  columns.forEach(o => {
    mapper[o.label] = o.prop
  })

  console.info('header', header)
  console.info('mapper', mapper)

  list.forEach(arr => {
    const obj = {}
    header.forEach((item, index) => {
      const val = arr[index] || ''
      obj[mapper[item]] = val + ''
    })
    dataList.push(obj)
  })

  return dataList

}
